package com.heima.juc.unlock;

import com.heima.juc.n2.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author : leimingchao
 * @date Date : 2022年02月12日 21:03
 */
@Slf4j(topic = "c.LockCas")
public class LockCas {

    /**
     * 0 : 没加锁
     * 1 : 加锁
     */
    private AtomicInteger state = new AtomicInteger(0);

    public static void main(String[] args) {

        LockCas lockCas = new LockCas();

        new Thread(() -> {
            log.debug("begin...");
            lockCas.lock();
            try {
                log.debug("lock....");
                Sleeper.sleep(1);
            } finally {
                lockCas.unlock();
            }
        },"t1").start();

        new Thread(() -> {
            log.debug("begin...");
            lockCas.lock();
            try {
                log.debug("lock....");
            } finally {
                lockCas.unlock();
            }
        },"t2").start();

    }

    public void lock() {
        while (true) {
            if (state.compareAndSet(0, 1)) {
                break;
            }
        }
    }

    public void unlock() {
        log.debug("unlock...");
        state.set(0);
    }

}
